﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using NModbus;

namespace Demo.Helper
{
    public class PlcHelper
    {
        private PlcHelper() { }

        // 私有静态实例，使用volatile确保内存可见性
        private static volatile PlcHelper instance;

        // 锁对象，用于线程同步
        private static readonly object lockObject = new object();

        // NModbus相关对象
        public TcpClient tcpClient;
        public IModbusMaster modbusMaster;
        public bool isConnected = false;

        // 静态访问点（双重检查锁定）
        public static PlcHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (lockObject)
                    {
                        if (instance == null)
                        {
                            instance = new PlcHelper();
                        }
                    }
                }
                return instance;
            }
        }

        // 初始化连接
        public bool Initialize(string ipAddress, int port)
        {
            try
            {
                // 断开已有连接
                if (isConnected)
                {
                    Disconnect();
                }

                // 创建TCP客户端并连接
                tcpClient = new TcpClient();
                var connectResult = tcpClient.BeginConnect(ipAddress, port, null, null);

                // 等待连接完成，设置超时时间
                var success = connectResult.AsyncWaitHandle.WaitOne(5000); // 5秒超时
                if (!success)
                {
                    Console.WriteLine("PLC连接超时");
                    tcpClient.Close();
                    return false;
                }

                // 完成连接
                tcpClient.EndConnect(connectResult);

                // 创建Modbus主机（NModbus 3.x的创建方式）
                var factory = new ModbusFactory();
                modbusMaster = factory.CreateMaster(tcpClient);

                // 设置超时时间
                modbusMaster.Transport.ReadTimeout = 10000; // 10秒
                modbusMaster.Transport.WriteTimeout = 5000; // 5秒

                isConnected = true;
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"PLC连接异常: {ex.Message}");
                isConnected = false;
                return false;
            }
        }

        // 断开连接
        public void Disconnect()
        {
            if (isConnected && tcpClient != null)
            {
                tcpClient.Close();
                modbusMaster = null;
                tcpClient = null;
                isConnected = false;
            }
        }
    }
}
